package middleware

import (
	"github.com/gin-gonic/gin"
	"go-malphite/app/common/constant"
	"go-malphite/app/common/enum"
	"go-malphite/app/service"
	"net/http"
)

// IsExistsUser 判断当前用户是否存在
func IsExistsUser() gin.HandlerFunc {
	return func(c *gin.Context) {
		exists := service.IsExistsUserById(c.GetInt64(constant.CurrentUserId))
		if !exists {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "用户不存在！",
			})
			c.Abort()
			return
		}
		c.Next()
	}
}

// IsAdminUser 判断当前用户是否为管理员
func IsAdminUser() gin.HandlerFunc {
	return func(c *gin.Context) {
		user, err := service.FindUserById(c.GetInt64(constant.CurrentUserId))
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "用户不存在！",
			})
			c.Abort()
			return
		}

		role, err := service.FindRoleById(user.RoleId)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "角色不存在！",
			})
			c.Abort()
			return
		}

		if role.RoleType != enum.RoleTypeAdmin.Get() {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "当前用户没有权限进行该操作！",
			})
			c.Abort()
			return
		}
		c.Next()
	}
}
